﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Configuration;

namespace Infrastructure
{
    public class OfficeHelper
    {
        //public static void ExportExcel(System.Data.DataTable dataTable, string excelFileName)
        //{
        //    object objOpt = Missing.Value;
        //    Application excel = new Application();
        //    excel.Visible = true;
        //    Workbooks workBooks = excel.Workbooks;
        //    Workbook workBook = workBooks.Add(objOpt);
        //    Sheets sheets = workBook.Sheets;
        //    Worksheet worksheet = (Worksheet)sheets[1];

        //    int rowIndex = 1, colIndex = 0;
        //    foreach (DataColumn column in dataTable.Columns)
        //    {
        //        colIndex++;
        //        excel.Cells[rowIndex, colIndex] = column.ColumnName;
        //    }
        //    foreach (DataRow row in dataTable.Rows)
        //    {
        //        rowIndex++;
        //        colIndex = 0;
        //        foreach (DataColumn column in dataTable.Columns)
        //        {
        //            colIndex++;
        //            excel.Cells[rowIndex, colIndex] = row[column.ColumnName].ToString();
        //        }
        //    }

        //    workBook.SaveAs(excelFileName, objOpt, null, null, false, false, XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
        //    workBook.Close(false, objOpt, objOpt);
        //    excel.Quit();
        //}

        public static void ExportCSV(System.Data.DataTable dataTable, string excelFileName)
        {
            StringBuilder sbData = new StringBuilder();

            foreach (DataColumn column in dataTable.Columns)
            {
                sbData.Append(column.ColumnName + ",");
            }
            sbData.AppendLine();

            foreach (DataRow row in dataTable.Rows)
            {
                foreach (DataColumn column in dataTable.Columns)
                {
                    sbData.Append(row[column].ToString() + ",");
                }
                sbData.AppendLine();
            }
            sbData.AppendLine();

            using (FileStream fs = new FileStream(excelFileName, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = System.Text.Encoding.GetEncoding(ConfigurationManager.AppSettings["CSVEncoding"]).GetBytes(sbData.ToString());
                fs.Write(buffer, 0, buffer.Length);
            }
        }
    }
}
